package com.lsz.crm.service;

import com.lsz.crm.base.BaseService;
import com.lsz.crm.mapper.ModuleMapper;
import com.lsz.crm.mapper.PermissionMapper;
import com.lsz.crm.mapper.RoleMapper;
import com.lsz.crm.pojo.Permission;
import com.lsz.crm.pojo.Role;
import com.lsz.crm.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author liushizhong
 * @Date 2021/10/28 21:03
 * @Version 1.0
 */

@Service
public class RoleService extends BaseService<Role,Integer> {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private ModuleMapper moduleMapper;

    /**
     * 查询⻆⾊列表
     * @return
     */
    public List<Map<String, Object>>queryAllRoles(Integer userId){

        return roleMapper.queryAllRoles(userId);
    }

    /**
     * 添加角色记录
     * @param role
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addRole(Role role){
        AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()),"请输⼊⻆⾊名!");
        Role temp = roleMapper.queryRoleByRoleName(role.getRoleName());
        AssertUtil.isTrue(null !=temp," 该⻆⾊已存在 !");
        // 设置默认值
        role.setIsValid(1);
        role.setCreateDate(new Date());
        role.setUpdateDate(new Date());
        AssertUtil.isTrue(roleMapper.insertSelective(role)<1,"⻆⾊记录添加失败!");
    }

    /**
     * 更新角色记录
     * @param role
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateRole(Role role){
        AssertUtil.isTrue(null==role.getId() || null == roleMapper.selectByPrimaryKey(role.getId()), "待修改的记录不存在!");
        AssertUtil.isTrue(StringUtils.isBlank(role.getRoleName()),"请输⼊⻆⾊名!");
        Role temp = roleMapper.queryRoleByRoleName(role.getRoleName());
        AssertUtil.isTrue(null !=temp && !(temp.getId().equals(role.getId()))," 该⻆⾊已存在!");
        // 设置默认值
        role.setUpdateDate(new Date());
        // 执行更新操作
        AssertUtil.isTrue(updateByPrimaryKeySelective(role) < 1,"⻆⾊记录更新失败!");
    }

    /**
     * 删除用户角色
     * @param ids
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteRole(Integer[] ids){
        AssertUtil.isTrue(null == ids || ids.length == 0,"请选择待删除的角色记录!");
        AssertUtil.isTrue(roleMapper.deleteBatch(ids) != ids.length,"角色记录删除失败!");
    }

    /**
     * 添加资源授权
     * @param roleId
     * @param ids
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addGrant(Integer roleId, Integer[] ids) {
        /**
         * 核⼼表-t_permission t_role(校验⻆⾊存在)
         *   如果⻆⾊存在原始权限 删除⻆⾊原始权限
         *   然后添加⻆⾊新的权限 批量添加权限记录到 t_permission
         */
        // 查询角色记录，判断是否存在
        Role temp = roleMapper.selectByPrimaryKey(roleId);
        AssertUtil.isTrue(null == temp,"待授权角色不存在！");
        // 通过角色 id 查询所有的权限
        Integer count = permissionMapper.countPermissionByRoleId(roleId);
        // 删除原有的权限
        if(count > 0){
            permissionMapper.deletePermissionsByRoleId(roleId);
        }
        // 添加权限
        if(null !=ids && ids.length>0){
            // 创建权限集合
            List<Permission> permissions=new ArrayList<Permission>();
            // 遍历资源id数组
            for (Integer id : ids) {
                Permission permission=new Permission();
                permission.setCreateDate(new Date());
                permission.setUpdateDate(new Date());
                permission.setModuleId(id);
                permission.setRoleId(roleId);
                // 授权码，从资源表中拿
                permission.setAclValue(moduleMapper.selectByPrimaryKey(id).getOptValue());
                permissions.add(permission);
            }
            // 批量添加
            AssertUtil.isTrue(permissionMapper.insertBatch(permissions) != permissions.size(),"权限分配失败！");
        }
    }
}
